package com.sh.rbac.core.encrypt.interceptor;

import com.sh.rbac.core.encrypt.encryptor.EncryptManager;
import com.sh.rbac.core.encrypt.properties.EncryptProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;
import java.util.Properties;

/**
 * mybatis 加密拦截器
 *
 * @author wb
 * @since 2025-10-24
 */

@Slf4j
@Component
@Intercepts({@Signature(type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class})})
public class MybatisEncryptInterceptor implements Interceptor {

    @Autowired
    private EncryptProperties encryptProperties;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        ParameterHandler parameterHandler = (ParameterHandler) invocation.getTarget();
        Object parameterObject = parameterHandler.getParameterObject();

        if (parameterObject != null) {
            EncryptManager.processEncryption(parameterObject, encryptProperties, true);
        }

        return invocation.proceed();
    }


    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 不需要特殊处理
    }
}
